<template>
  <div>
    <el-dialog :close-on-click-modal="true" title="文件预览" type="primary" v-model="props.previewDialog"
      width="80%" left @close="closePreview">
      <img v-if="dialogData.fileType == 1" :src="dialogData.fileUrl" alt="" class="imgBox">
      <div v-if="dialogData.fileType == 2" id="luckysheet" class="excalBox"></div>
      <div v-if="dialogData.fileType == 3" id="bodyContainer"></div>
      <iframe v-if="dialogData.fileType == 4" :src="dialogData.fileUrl" class="pdfBox"></iframe>
      <video v-if="dialogData.fileType == 5" :src="dialogData.fileUrl" controls="true" autoplay="true"
        loop="true">
      </video>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" v-on:click="closePreview">
            关闭
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { defineProps, defineEmits, watch, nextTick } from "vue";
  import { reactive } from "vue";
  import { previewFile } from "@/api/work.js"
  import { ElNotification } from "element-plus";
  import LuckyExcel from 'luckyexcel'
  import { renderAsync } from "docx-preview";
  let props = defineProps({
    previewDialog: {
      type: Boolean,
    },
    file: {
      type: Object,
    }
  });
  const emit = defineEmits(['closePreview'])
  const dialogData = reactive({
    fileType: '', // 1 图片 2 excal 3 docx 4 pdf 5 mp4
    fileUrl: ''
  })
  watch(
    () => props.previewDialog,
    () => {
      if(props.previewDialog){
        handleLook();
      }
    },
    { deep: true, immediate: true }
  ) 
  //预览
  const handleLook = () => {
    let row = props.file
    let arr = row.fileType.split('.');
    let fileType = arr[arr.length - 1];

    dialogData.previewDialog = true

    nextTick(() => {

      dialogData.fileType = fileType === "png" || fileType === "jpg" || fileType === "jpeg" ? 1
                            : fileType === "xlsx" ? 2
                            : fileType === "docx" ? 3
                            : fileType === "pdf" ? 4
                            : fileType === "mp4" ? 5 : ''

      let type = dialogData.fileType

      if (type == 1 || type == 4 || type == 5) {
        dialogData.fileUrl = row.url
      } else if (type == 2) {
        excalPreview(row)
      } else if (type == 3) {
        docxPreview(row.url)
      }
    })
  }
  // excal预览
  const excalPreview = (row) => {
    previewFile(row.url).then((res) => {
      if (res.code === 200) {
        let prefix = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,'
        let url = prefix + res.body.imageIo
        const files = [base64ToFile(url)];
        if (files == null || files.length == 0) {
          alert("No files wait for import");
          return;
        }
        let name = files[0].name;
        let suffixArr = name.split("."),
          suffix = suffixArr[suffixArr.length - 1];
        if (suffix != "xlsx") {
          alert("Currently only supports the import of xlsx files");
          return;
        }
        LuckyExcel.transformExcelToLucky(
          files[0],
          function (exportJson, luckysheetfile) {
            if (exportJson.sheets == null || exportJson.sheets.length == 0) {
              alert(
                "Failed to read the content of the excel file, currently does not support xls files!"
              );
              return;
            }
            window.luckysheet.destroy();
            window.luckysheet.create({
              container: "luckysheet", //luckysheet is the container id
              showinfobar: false, // 是否显示顶部信息栏
              showsheetbar: true, // 是否显示底部sheet按钮
              data: exportJson.sheets,
              title: exportJson.info.name,
              userInfo: exportJson.info.name.creator,
              showtoolbar: false, // 是否显示工具栏
              cellRightClickConfig: {
                copy: false, // 复制
                copyAs: false, // 复制为
                paste: false, // 粘贴
                insertRow: false, // 插入行
                insertColumn: false, // 插入列
                deleteRow: false, // 删除选中行
                deleteColumn: false, // 删除选中列
                deleteCell: false, // 删除单元格
                hideRow: false, // 隐藏选中行和显示选中行
                hideColumn: false, // 隐藏选中列和显示选中列
                rowHeight: false, // 行高
                columnWidth: false, // 列宽
                clear: false, // 清除内容
                matrix: false, // 矩阵操作选区
                sort: false, // 排序选区
                filter: false, // 筛选选区
                chart: false, // 图表生成
                image: false, // 插入图片
                link: false, // 插入链接
                data: false, // 数据验证
                cellFormat: false // 设置单元格格式
              },
            });
          }
        );
      } else {
        ElNotification({
          title: '提示',
          message: res.message ? res.message : '服务器异常',
          type: 'warning'
        })
        if (res.code === 100007 || res.code === 100008 || res.code === 100011) {
          store.dispatch('app/logout')
        }
      }
    }).catch(() => {})
  }
  // xlsx 数据转base64
  const base64ToFile = (base64) => {
    let fileType = {
      "vnd.ms-excel": "xls",
      "vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
      "vnd.ms-excel.sheet.macroEnabled.12": "xlsm",
      "vnd.ms-excel.sheet.binary.macroEnabled.12": "xlsb",
      "vnd.oasis.opendocument.spreadsheet": "ods",
    };
    const name = "工作表";
    if (typeof base64 != "string") {
      return;
    }
    var arr = base64.split(",");
    var type = arr[0].match(/:(.*?);/)[1];
    console.log(type.split("/")[1], 'fileType[type.split("/")[1]]');
    var fileExt = fileType[type.split("/")[1]] || "xls";
    var bstr = atob(arr[1]);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File(
      [
        new Blob([u8arr], {
          type: type,
        }),
      ],
      `${name}.` + fileExt,
      {
        type: type,
      }
    );
  }
  // word预览 url数据 转换 blob
  const docxPreview = (url) => {
    fetch(url).then(response => response.blob()).then(blob => { // 将响应转换为Blob
      // 现在你有了一个Blob对象，可以根据需要使用它
      nextTick(() => {
        let file = blob
        let fr = new FileReader()
        fr.readAsArrayBuffer(file)
        fr.addEventListener('loadend', (e) => {
          let buffer = e.target.result
          docxRender(buffer)
        })
      })
    }).catch(error => {
      // 处理错误
      ElNotification({
        title: 'Error fetching file',
        message: error,
        type: 'warning'
      })
    });
  }
  // word预览方法
  const docxRender = (buffer) => {
    let docxOptions = {
      className: 'aaa',
      inWrapper: true,
      ignoreWidth: false,
      ignoreHeight: false,
      ignoreFonts: false,
      breakPages: true,
      ignoreLastRenderPageBreak: true,
      experimental: false,
      trimXmDeclaration: true,
      useBase64URL: false,
      useMathMLPolyfill: false,
      showChanges: false,
      debug: false
    }
    let bodyContainer = document.getElementById("bodyContainer")
    renderAsync(
      buffer,
      bodyContainer,
      null,
      docxOptions
    ).then(res => {
      console.log('res', res);
    })
  }
  // 关闭dialog
  const closePreview = () => {
    if (dialogData.fileType == 5) {
      let video = document.querySelector("video")
      video.currentTime = 0
    }
    emit('closePreview')
  }
</script>

<style lang='less' scoped>
  :deep(.el-dialog__body) {
    height: 600px;
    padding-bottom: 10px !important;
    overflow: auto;
  }
  .imgBox{
    width: 100%;
    height: auto;
  }
  .excalBox{
    width:100%;
    height:555px;
    margin:0;
    padding:0;
  }
  #bodyContainer{
    height:555px;
    overflow: auto;
  }
  .pdfBox{
    width: 100%;
    height: 555px;
  }
  video{
    width: 100%;
    height: 555px;
    margin: 0 auto;
  }
</style>